# I know, confusing class/file name

require 'platform'

class NetfluxdClient
  def initialize(host = 'localhost', port = Conf.Port)
    @host = host
    @port = port
  end

  def start
    if Platform::OS == :win32
      system('cmd.exe /c ' + RAILS_ROOT + '\\script\\runner ' + RAILS_ROOT + '\\script\\netfluxd.rb')
    else
      system(RAILS_ROOT + '/script/runner ' + RAILS_ROOT + '/script/netfluxd.rb &')
    end
  end

  def respond_to?(symbol)
    true
  end

  def method_missing(symbol, *args)
    begin
      return super(symbol, *args)
    rescue
    end

    name = symbol.id2name

    name += ' ' + args.join(' ') if not args.empty?

    # Get netfluxd status
    begin
      socket = TCPSocket.new(@host, @port)
      raise "unable to connect to #{@host}:#{@port}" if not socket
  
      socket.gets
      socket.puts name
      result = socket.gets.chomp[2..-1]
      socket.close

    rescue SystemCallError => e
      result = 'not running (<i>' + e.to_s + '</i>)'
    rescue RuntimeError => e
      result e.to_s
    end

    result
  end

end
